package com.blast.manager.ask

import android.text.TextUtils
import android.view.KeyEvent
import com.blast.manager.R
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lzy.okgo.model.HttpParams
import com.wxl.common.base.AbsActivity
import com.wxl.common.http.OkGoApi
import com.wxl.common.http.SerialHttpCallback
import com.wxl.common.room.entity.QuestionEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.NetWorkUtils
import com.wxl.common.util.ObservableUtil
import kotlinx.android.synthetic.main.activity_ask_layout.*

class QuestionActivity : AbsActivity(){

    var loadDialog: BasePopupView?=null

    override fun getCreateContentViewId(): Int {
        return R.layout.activity_ask_layout
    }

    override fun onCreateViewChanged() {
        val id = intent.getStringExtra("id")
        if(!TextUtils.isEmpty(id)) {
            loadAsk(id!!)
        }

        askBack.setOnClickListener {
            finish()
        }
    }

    private fun loadAsk(id:String){
        if(NetWorkUtils.isNetWorkAvailable(this)){
            loadDialog = XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .asLoading("正在加载问题列表...")
                .show()
            addPop(loadDialog as BasePopupView)
            val param = HttpParams()
            param.put("action","getQuestionDetails")
            param.put("id",id)
            OkGoApi.api.post()
                .params(param)
                .execute(object : SerialHttpCallback<QuestionEntity>("List"){
                    override fun loadDataSuccess(datas: ArrayList<QuestionEntity>) {
                        DBHelper.setNewAsk(object : ObservableUtil.Companion.OnNextCallback<Boolean>(){
                            override fun onNext(t: Boolean) {
                                loadDBAsk(id)
                            }
                        },*datas.toTypedArray())
                    }

                    override fun loadDataFailed(e: Throwable) {
                        loadDBAsk(id)
                    }
                })
        } else {
            loadDBAsk(id)
        }
    }

    /**
     * 加载本地问题详情
     */
    private fun loadDBAsk(id:String){
        DBHelper.queryAskById(object : ObservableUtil.Companion.OnNextCallback<List<QuestionEntity>>(){
            override fun onNext(t: List<QuestionEntity>) {
                loadDialog?.dismiss()
                if(t.isNotEmpty()){
                    askText.text = t[0].details
                }
            }
        },id)
    }


    override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_F1 || keyCode == KeyEvent.KEYCODE_BACK){
            askBack.performClick()
        }
        return true
    }
}